package com.zlzlib.libui.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import java.io.File;
import java.io.IOException;

/**
 * Created by zlz on 2018/6/6.
 */
public class IntentUtil {

    /**
     * 通过类名启动Activity
     *
     * @param pClass
     */
    public static void openActivity(Context context, Class<?> pClass) {
        openActivity(context, pClass, null);
    }

    /**
     * 通过类名启动Activity，并且含有Bundle数据
     *
     * @param pClass
     * @param pBundle
     */
    public static void openActivity(Context context, Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(context, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        context.startActivity(intent);
    }

    /**
     * 通过Action启动Activity
     *
     * @param pAction
     */
    public static void openActivity(Context context, String pAction) {
        openActivity(context, pAction, null);
    }

    /**
     * 通过Action启动Activity，并且含有Bundle数据
     *
     * @param pAction
     * @param pBundle
     */
    public static void openActivity(Context context, String pAction, Bundle pBundle) {
        Intent intent = new Intent(pAction);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        context.startActivity(intent);
    }

    /**
     * 通过Intent跳转
     *
     * @param context
     * @param Intent
     */
    public static void openActivity(Context context, Intent Intent) {
        if (Intent == null) {
            return;
        }
        context.startActivity(Intent);
    }

    public static void openActivityResult(Activity activity, Class<?> pClass, int req) {
        Intent intent = new Intent();
        intent.setClass(activity, pClass);
        activity.startActivityForResult(intent, req);
    }

    public static void openActivityResult(Fragment activity, Class<?> pClass, int req) {
        Intent intent = new Intent();
        intent.setClass(activity.getContext(), pClass);
        activity.startActivityForResult(intent, req);
    }

    public static void openActivityResultIntent(Activity activity, Intent intent, int req) {
        activity.startActivityForResult(intent, req);
    }

    public static void openActivityResultIntent(Fragment fragment, Intent intent, int req) {
        fragment.startActivityForResult(intent, req);
    }

    public static void openActivityResult(Activity activity, Intent intent, int req) {
        activity.startActivityForResult(intent, req);
    }

    /**
     * 直接拨打电话 要请求权限
     *
     * @param context
     * @param phone
     */
    @SuppressLint("MissingPermission")
    public static void openCall(Context context, String phone) {
        Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));
        //判断是否有权限
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        context.startActivity(dialIntent);
    }

    /*
    跳转到打电话页面
     */
    public static boolean openCallPage(Context context, String phone) {
        //跳转到拨号界面，同时传递电话号码
        try {
            Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(phone));
            dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(dialIntent);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 发送短信页面
     *
     * @param phone
     */

    public static boolean sendSmsPage(Context context, String phone) {
        try {
            Uri smsToUri = Uri.parse("smsto:" + phone);
            Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("sms_body", "");
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 发送邮件 页面
     *
     * @param phone
     */
    public static boolean sendMailPage(Context context, String phone) {
        try {
            Intent i = new Intent(Intent.ACTION_SEND);
            // i.setType("text/plain"); //模拟器请使用这行
//        i.setData(Uri.parse(phone));
            i.setType("message/rfc822"); // 真机上使用这行
            i.putExtra(Intent.EXTRA_EMAIL, new String[]{phone});
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        i.putExtra(Intent.EXTRA_SUBJECT, "");
//        i.putExtra(Intent.EXTRA_TEXT, " ");
            context.startActivity(Intent.createChooser(i, "Select email application."));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 开启蓝牙的intent
     *
     * @return
     */
    public static Intent getOpenBlueTooth() {
        return new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    }


    /**
     * @param context
     * @return 跳转到系统权限设置页面
     */
    public static Intent getAppDetailSettingIntent(Context context, boolean isNewTask) {
        Intent localIntent = new Intent();
        if (isNewTask) {
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        return localIntent;
    }


    /**
     * @param isMultiple 是否多选
     * @return 文件选择选择Intent
     */
    public static Intent getFileSelectIntent(boolean isMultiple) {
        Intent intent = new Intent();
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, isMultiple);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        return intent;
    }


    /**
     * @param isMultiple 是否多选
     * @return 照片选择Intent
     */
    public static Intent getImgSelectIntent(boolean isMultiple) {
        Intent intent = new Intent();
        //图片多选
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, isMultiple);
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        return intent;
    }

    /**
     * @return 获得照相Intent, 自定义图片保存路径
     */
    public static Intent getCameraIntent(Uri uri) {
        Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        it.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        if (null != uri) {
            it.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        return it;
    }

    /**
     * 裁剪图片
     */
    public static void cropPhoto(Fragment fragment, Uri uri, String path, int req_code) {
        fragment.startActivityForResult(getCropIntent(uri, path), req_code);
    }

    /**
     * 裁剪图片
     */
    public static void cropPhoto(Activity activity, Uri uri, String path, int req_code) {
        activity.startActivityForResult(getCropIntent(uri, path), req_code);
    }

    /**
     * 裁剪图片
     */
    public static Intent getCropIntent(Uri uri, String path) {
        // 创建File对象，用于存储裁剪后的图片，避免更改原图
        File file = new File(path);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri outputUri = Uri.fromFile(file);
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        //裁剪图片的宽高比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
        intent.putExtra("crop", "true");//可裁剪
        // 裁剪后输出图片的尺寸大小
        //intent.putExtra("outputX", 400);
        //intent.putExtra("outputY", 200);
        intent.putExtra("scale", true);//支持缩放
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());//输出图片格式
        intent.putExtra("noFaceDetection", true);//取消人脸识别
        return intent;
    }

    /**
     * @param file 文件
     * @return 从文件获取uri
     */
    public static Uri getUriFromFile(Context context, File file) {
        Uri uri = null;
        try {
            //判断是否大于7.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //7.0
                uri = FileProvider.getUriForFile(context, context.getPackageName(), file);
            } else {
                uri = Uri.fromFile(file);
            }
        } catch (Exception ignored) {
        }
        return uri;
    }

    /**
     * 后台启动activity
     *
     * @param context
     * @param cla
     */
    public static void startActivityBack(Context context, Class cla) {
        Intent intents = context.getPackageManager()
                .getLaunchIntentForPackage(context.getPackageName());
        intents.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intents.setClass(context, cla);
        context.startActivity(intents);
    }

    /**
     * 后台启动activity
     *
     * @param context
     * @param cla
     * @param bundle
     */
    public static void startActivityBack(Context context, Class cla, Bundle bundle) {
        Intent intents = context.getPackageManager()
                .getLaunchIntentForPackage(context.getPackageName());
        intents.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intents.setClass(context, cla);
        intents.putExtras(bundle);
        context.startActivity(intents);
    }

    /**
     * 跳转
     *
     * @param context      上下文
     * @param activityPath 要跳转的类的全包名.类名
     * @param bundle       要传递的参数
     */
    public static boolean jump(Context context, String activityPath, @Nullable Bundle bundle) {
        if (TextUtils.isEmpty(activityPath))
            return false;
        try {
            Intent intent = new Intent(context, Class.forName(activityPath));
            if (bundle != null) intent.putExtras(bundle);
            context.startActivity(intent);
            return true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean jumpIntent(Context context, String activityPath, @NonNull Intent intent) {
        if (TextUtils.isEmpty(activityPath))
            return false;
        try {
            intent.setClass(context, Class.forName(activityPath));
            context.startActivity(intent);
            return true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @return 网络设置页面跳转的intent
     */
    public static Intent getWirelessSettingIntent() {
        return new Intent(Settings.ACTION_WIRELESS_SETTINGS);
    }
}
